from tortoise.expressions import Q

from app.controllers.customer.users import users_controller
from app.core.crud import CRUDBase
from app.models import OrdersGoods, Goods, CustomerGrow, CustomerUser
from app.models.marketing import Commission
from app.schemas.marketing import CommissionCreate,CommissionUpdate
from decimal import Decimal


class CommissionController(CRUDBase[Commission, CommissionCreate, CommissionUpdate]):
    def __init__(self):
        super().__init__(model=Commission)

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs =  await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict(exclude_fields=["updated_at","deleted_at"]) for obj in objs]
        return total, data

    async def do_detail(self,data_id:int):
        obj = await self.get(id=data_id)
        data = await obj.to_dict()
        return data

    async def do_create(self, obj_in: CommissionCreate):
        await self.create(obj_in=obj_in)
        await users_controller.update_money(type=4, user_id=obj_in.user_id)
        return True

    async def do_update(self, obj_in: CommissionUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        await users_controller.update_money(type=4, user_id=obj_in.user_id)
        return True

    async def do_delete(self, data_id: int):
        user_id = await self.model.filter(id=data_id).first().values("user_id")
        await self.remove(id=data_id)
        await users_controller.update_money(type=4, user_id=user_id['user_id'])
        return True


    async def do_status(self,data_id: int,status: int):
        print(f"生成收益{data_id}-{status}")
        if status == 1:
            ##开始生成收益
            ##1.查询order_goods
            order_goods = await OrdersGoods.filter(id=data_id).first().values("id","order_id","goods_id","price","user_id")
            ##2.查询商品收益规则
            goods = await Goods.filter(id=order_goods['goods_id']).first().values("grow_id")
            if goods['grow_id']:
                order_goods['grow_id'] = goods['grow_id']
            else:
                return
            ##3.查询详细规则模板
            grow = await CustomerGrow.filter(id=order_goods['grow_id']).first().values("type","routers")
            grow_type = grow['type']
            grow_routers = grow['routers']
            for router in grow_routers:
                num = router.get('num')##比例
                level = router.get('level')##生成等级
                name = router.get('name')##会员类型
                ##计算受益人id
                user_id = await self.get_sy_uid(order_uid=order_goods['user_id'],level=level,name=name)
                ##计算价格
                if grow_type==2:
                    price = Decimal(num)
                else:
                    price = order_goods['price']* Decimal(num) / Decimal(100)

                commission_item = {
                    "user_id": user_id,
                    "user_level": name,
                    "level": level,
                    "price": price,
                }
                if price>0 and user_id>0:
                    await self.insert_sy(order_goods,commission_item)
        else:
            search = Q(orders_goods_id=data_id)
            await self.remove_q(search)
        return True

    async def insert_sy(self, order_goods:[],commission_item:[]):
        commission_data = {
            "orders_id": order_goods['order_id'],
            "orders_goods_id": order_goods['id'],
            "goods_id": order_goods['goods_id'],
            "goods_price": order_goods['price'],
            "orders_user_id": order_goods['user_id'],
            "grow_id": order_goods["grow_id"],
            "user_id": commission_item["user_id"],  ##受益人id
            "user_level": commission_item["user_level"],  ##受益人类型
            "level": commission_item["level"],  ##受益等级
            "price": commission_item["price"],  ##受益金额
            "status": 0,
        }
        commission_in = CommissionCreate(**commission_data)
        await self.do_create(commission_in)
        return True

    async def get_sy_uid(self,order_uid:int,level:int,name:int):
        user_id = order_uid
        # 初始化变量
        i = 0
        do_while_flag = True
        while do_while_flag:
            i += 1
            parent = await CustomerUser.filter(id=user_id).first().values("parent_id")
            user_id = parent['parent_id']
            # 检查是否满足退出循环的条件，如果满足则设置标志为False，下一次循环时会退出
            if i > level:
                do_while_flag = False
        parent_level = await CustomerUser.filter(id=user_id).first().values("role_id")
        if name != parent_level["role_id"]:
            user_id = 0
        return user_id



commission_controller = CommissionController()
